<template>
  <a-modal
    title="执行出库"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消"
    okText="确认出库"
  >
    <div v-if="model.id">
      <!-- 出库单基本信息 -->
      <a-descriptions title="出库单信息" :column="2" size="small" bordered style="margin-bottom: 16px;">
        <a-descriptions-item label="出库单号">{{ model.outboundNo }}</a-descriptions-item>
        <a-descriptions-item label="客户名称">{{ model.customerName }}</a-descriptions-item>
        <a-descriptions-item label="出库仓库">{{ model.warehouseName }}</a-descriptions-item>
        <a-descriptions-item label="出库总数量">{{ model.totalQuantity }}</a-descriptions-item>
      </a-descriptions>

      <!-- 出库明细确认 -->
      <a-card title="出库明细确认" size="small">
        <a-table
          :columns="detailColumns"
          :dataSource="detailList"
          :pagination="false"
          size="small"
          rowKey="id"
        >
          <template slot="actualQuantity" slot-scope="text, record, index">
            <a-input-number
              v-model="detailList[index].actualQuantity"
              :min="0"
              :max="record.outboundQuantity"
              size="small"
              style="width: 80px;"
            />
          </template>
          <template slot="qualityStatus" slot-scope="text, record, index">
            <a-select
              v-model="detailList[index].qualityStatus"
              size="small"
              style="width: 80px;"
            >
              <a-select-option :value="1">合格</a-select-option>
              <a-select-option :value="2">不合格</a-select-option>
            </a-select>
          </template>
        </a-table>
      </a-card>

      <a-divider />

      <!-- 执行信息 -->
      <a-form-model
        ref="form"
        :model="executeForm"
        :rules="validatorRules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-model-item label="物流公司" prop="logisticsCompany">
          <a-input v-model="executeForm.logisticsCompany" placeholder="请输入物流公司" />
        </a-form-model-item>

        <a-form-model-item label="物流单号" prop="trackingNumber">
          <a-input v-model="executeForm.trackingNumber" placeholder="请输入物流单号" />
        </a-form-model-item>

        <a-form-model-item label="执行备注" prop="executeRemark">
          <a-textarea
            v-model="executeForm.executeRemark"
            placeholder="请输入执行备注"
            :rows="3"
            :maxLength="500"
            showCount
          />
        </a-form-model-item>
      </a-form-model>
    </div>
  </a-modal>
</template>

<script>
export default {
  name: 'OutboundExecuteModal',
  data() {
    return {
      visible: false,
      confirmLoading: false,
      model: {},
      detailList: [],
      executeForm: {
        logisticsCompany: '',
        trackingNumber: '',
        executeRemark: ''
      },
      validatorRules: {
        logisticsCompany: [{ required: true, message: '请输入物流公司!' }],
        trackingNumber: [{ required: true, message: '请输入物流单号!' }]
      },
      detailColumns: [
        { title: '订单号', dataIndex: 'orderNo', width: 120 },
        { title: '门窗系列', dataIndex: 'windowSeries', width: 120 },
        { title: '库位编码', dataIndex: 'locationCode', width: 100 },
        { title: '批次号', dataIndex: 'batchNo', width: 100 },
        { title: '计划数量', dataIndex: 'outboundQuantity', width: 80 },
        {
          title: '实际数量',
          dataIndex: 'actualQuantity',
          width: 100,
          scopedSlots: { customRender: 'actualQuantity' }
        },
        {
          title: '质量状态',
          dataIndex: 'qualityStatus',
          width: 100,
          scopedSlots: { customRender: 'qualityStatus' }
        }
      ]
    }
  },
  methods: {
    show(record) {
      this.visible = true
      this.model = { ...record }
      this.executeForm = {
        logisticsCompany: record.logisticsCompany || '',
        trackingNumber: record.trackingNumber || '',
        executeRemark: ''
      }
      this.loadDetailList()
    },
    close() {
      this.visible = false
      this.model = {}
      this.detailList = []
      this.executeForm = {
        logisticsCompany: '',
        trackingNumber: '',
        executeRemark: ''
      }
      this.$refs.form && this.$refs.form.resetFields()
    },
    async loadDetailList() {
      if (!this.model.id) return
      
      try {
        // 加载出库明细
        // const result = await this.$http.get(`/wms/finished-goods/outbound/detail/${this.model.id}`)
        // this.detailList = result.result?.map(item => ({
        //   ...item,
        //   actualQuantity: item.outboundQuantity,
        //   qualityStatus: item.qualityStatus || 1
        // })) || []

        // 模拟数据
        this.detailList = []
      } catch (error) {
        this.$message.error('加载明细失败：' + error.message)
      }
    },
    handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return

        // 验证实际数量
        const hasInvalidQuantity = this.detailList.some(item =>
          !item.actualQuantity || item.actualQuantity <= 0 || item.actualQuantity > item.outboundQuantity
        )
        if (hasInvalidQuantity) {
          this.$message.error('请检查实际出库数量，不能为空且不能超过计划数量！')
          return
        }

        this.confirmLoading = true
        try {
          // const params = {
          //   id: this.model.id,
          //   logisticsCompany: this.executeForm.logisticsCompany,
          //   trackingNumber: this.executeForm.trackingNumber,
          //   executeRemark: this.executeForm.executeRemark,
          //   detailList: this.detailList.map(item => ({
          //     id: item.id,
          //     actualQuantity: item.actualQuantity,
          //     qualityStatus: item.qualityStatus
          //   }))
          // }

          // const result = await this.$http.post(`/wms/finished-goods/outbound/execute/${this.model.id}`, params)

          this.$message.success('出库执行成功！')
          this.$emit('ok')
          this.close()
        } catch (error) {
          this.$message.error('执行出库失败：' + error.message)
        } finally {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>
